package handler

import (
	"com-man-sys/model"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"path/filepath"
	"strconv"
)

func GetGoodById(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var goods []model.Goods
	model.DB.Where("id=?", id).Find(&goods)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"goods": goods,
	})
	return
}
func GetGood(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var goods []model.Goods
	model.DB.Offset(offset).Limit(size).Find(&goods)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"goods": goods,
	})
	return
}

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	ext := filepath.Ext(file.Filename)
	if ext != ".jpg" && ext != ".png" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品图片限制jpg、png",
		})
		return
	}
	filename := uuid.NewString() + ".png"
	path := "static/img/" + filename
	// 上传文件至指定的完整文件路径
	err := c.SaveUploadedFile(file, "./"+path)
	URL := "http://127.0.0.1:8000/" + path
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品图片上传失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "商品图片上传成功",
			"URL":  URL,
		})
		return
	}

}
func CreateGoods(c *gin.Context) {
	name := c.PostForm("name")
	price, _ := strconv.Atoi(c.PostForm("price"))
	content := c.PostForm("content")
	img := c.PostForm("img")
	if name == "" || price == 0 || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品名称,价格,内容,图片不能为空",
		})
		return
	}
	if len(name) > 10 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品名称长度10字以内",
		})
		return
	}
	if len(content) > 50 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "正文内容50字以内",
		})
		return
	}
	data := model.Goods{
		Name:    name,
		Price:   float64(price),
		Content: content,
		Img:     img,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
